package datastructure;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author ZhangCuirong
 * @Date 2025/9/4 12:30
 * @description:
 */
public class ProductOfNumbers {
    List<Integer> preProject = new ArrayList<>();

    public ProductOfNumbers() {
        preProject.add(1);
    }

    public void add(int num) {
        if (num == 0) {
            preProject.clear();
            preProject.add(1);
        } else {
            preProject.add(preProject.get(preProject.size() - 1) * num);
        }
    }

    public int getProduct(int k) {
        if (k > preProject.size() - 1) {
            return 0;
        }
        return preProject.get(preProject.size() - 1) / preProject.get(preProject.size() - k - 1);
    }

    public static void main(String[] args) {
        ProductOfNumbers productOfNumbers = new ProductOfNumbers();
        productOfNumbers.add(3);        // [3]
        productOfNumbers.add(0);        // [3,0]
        productOfNumbers.add(2);        // [3,0,2]
        productOfNumbers.add(5);        // [3,0,2,5]
        productOfNumbers.add(4);        // [3,0,2,5,4]
        System.out.println(productOfNumbers.getProduct(2)); // 返回 20 。最后 2 个数字的乘积是 5 * 4 = 20
        System.out.println(productOfNumbers.getProduct(3)); // 返回 40 。最后 3 个数字的乘积是 2 * 5 * 4 = 40
        System.out.println(productOfNumbers.getProduct(4)); // 返回  0 。最后 4 个数字的乘积是 0 * 2 * 5 * 4 = 0
        productOfNumbers.add(8);        // [3,0,2,5,4,8]
        System.out.println(productOfNumbers.getProduct(2)); // 返回 32 。最后 2 个数字的乘积是 4 * 8 = 32
    }
}
